from . import app_weixin_pay
from .conn_mysql import ConnectMysql
from .setting import config
from flask import request, render_template
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from weixin import Weixin, WeixinError



weixin = Weixin(config)

@app_weixin_pay.route("/index")
def index():

    return render_template('pay.html')

@app_weixin_pay.route("/jsapi")
def pay_jsapi():
    """微信网页支付请求发起"""
    openid = request.args.get('openid')
    body = request.args.get('body')
    total_fee = request.args.get('total_fee')
    
    if not all((openid, body, total_fee)):

        return {
                'status': -1,
                'errorCode': '1002',
                'errorMsg': '参数没有到位',
                'resultBody': None
            }

    try:

        out_trade_no = weixin.nonce_str
        raw = weixin.jsapi(openid=openid, body=body, out_trade_no=out_trade_no, total_fee=total_fee)
        # print(raw)#{'package': 'prepay_id=wx131649165306681b1592d03b1839799800', 'appId': 'wx90014a2b7a9ab7f2', 'signType': 'MD5', 'timeStamp': '1586767756', 'nonceStr': 'vBNkDYLmodxPeCVNDz0SAbkyIqXoSK4A', 'sign': '3F950C1AD3FBE2F9551E92BDA406473C'}
        #定单入库
        conn_obj = ConnectMysql()#链接数据库
        sql = 'insert into prepay(prepay_id, openid, body, total_fee) values (%s,%s,%s,%s)'
        conn_obj.insert_info(
            sql, 
            (raw['package'].replace('prepay_id=', ''), openid, body, total_fee)
        )
        conn_obj.close()

        
        
        # return jsonify(
        #     {
        #         'status': 1,
        #         'errorCode': None,
        #         'errorMsg': None,
        #         'resultBody': raw
        #     }
        # )

        return render_template('repay.html', raw = raw)


    except WeixinError as e:
        
        return {
                'status': -1,
                'errorCode': '1003',
                'errorMsg': e.args[0],
                'resultBody': None
            }


@app_weixin_pay.route("/notify", methods = ['POST', "GET"])
def pay_notify():
    """
    微信异步通知
    """
    conn_obj = ConnectMysql()#链接数据库
    data = weixin.to_dict(request.data)
    with open('pay_notify.log', 'a') as f:
        f.write('\n')
        f.write(str(data))
        f.write('\n')
    openid = data.get('openid')
    sql_preapy_info = 'SELECT * FROM prepay WHERE openid=%s ORDER BY id DESC LIMIT 0,1' 

    preapy_info = conn_obj.select_one(sql_preapy_info, (openid,))

    preapy_id = preapy_info.get('id')

    if preapy_info.get('status') == "SUCCESS":

        conn_obj.close()

        return weixin.reply("OK", True)

    elif preapy_info.get('status') == "FAIL":

        conn_obj.close()

        return weixin.reply("已经失败", False)

    sql_prepay_status = 'UPDATE prepay SET status=%s WHERE id=%s'#更改prepay状态的sql

    #{'return_code': 'SUCCESS', 'return_msg': 'OK', 'appid': 'wx2421b1c4370ec43b', 'mch_id': '10000100', 'nonce_str': 'IITRi8Iabbblz1Jc', 'openid': 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o', 'sign': '7921E432F65EB8ED0CE9755F0E86D72F', 'result_code': 'SUCCESS', 'prepay_id': 'wx201411101639507cbf6ffd8b0779950874', 'trade_type': 'JSAPI'}
    if not weixin.check(data):#签名验证失败
        conn_obj.update_info(sql_prepay_status, ('FAIL', preapy_id))#更改定单状态为失败
        conn_obj.close()
        return weixin.reply("签名验证失败", False)
    
    
    return_code = data.get('return_code')
    result_code = data.get('result_code')

    if result_code == 'SUCCESS' and return_code == 'SUCCESS': #付费成功

        

        conn_obj.update_info(sql_prepay_status, ('SUCCESS', preapy_id))#更改定单新动态为成功

        total_fee = int(preapy_info.get('total_fee'))#付费金额


        if total_fee == 1:

            add = 1
        if total_fee == 100:

            add = 4

        if total_fee == 200:

            add = 10

        up_sql = "UPDATE company SET consumption_surplus=consumption_surplus+%s WHERE openid=%s"

        conn_obj.update_info(up_sql, (add, openid))#添加对应次数

        conn_obj.close()

        return weixin.reply("OK", True)

    else:#付费失败

        conn_obj.update_info(sql_prepay_status, ('FAIL', prepay_id))#更改定单状态为失败
        conn_obj.close()

        return weixin.reply(f"result_code: {result_code},return_code: {return_code}", False)

    